<template>
  <div class="tags-view">
    <el-icon v-show="isShowArrow" class="arrow-left" @click="handleScroll('left')">
      <ArrowLeft />
    </el-icon>
    <div ref="scrollbarDom" class="scroll-container">
      <div class="tags-view-list">
        <div
          class="tags-view-item"
          :class="{ active: isActive(tag) }"
          v-for="(tag, index) in tagsViewStore.tagsViews"
          :key="tag.path"
          @mouseenter.prevent="onMouseenter(index)"
          @mouseleave.prevent="onMouseleave(index)">
          <span class="tag-title">{{ tag.meta?.title }}</span>
          <span v-if="!isAffix(tag)" @click.stop="closeSelectedTag(tag)" class="el-icon-close">
            <el-icon><Close /></el-icon>
          </span>
          <span :ref="'schedule' + index"></span>
        </div>
      </div>
    </div>
    <el-icon v-show="isShowArrow" class="arrow-right" @click="handleScroll('right')">
      <ArrowRight />
    </el-icon>
  </div>
</template>
<script setup lang="ts">
import { ref, toRaw, onMounted, watch, getCurrentInstance } from "vue";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useTagsViewStoreHook } from "@/store/modules/tags-view";
import { useResizeObserver } from "@/hooks/useResizeObserver";
import {
  type RouteLocationNormalized,
  type RouteLocationNormalizedLoaded,
  useRouter,
  useRoute,
  RouteRecordRaw
} from "vue-router";

const router = useRouter();
console.log(router, "router");

const route = useRoute();
const isShowArrow = ref(false);
const tagsViewStore = useTagsViewStoreHook();
const handleScroll = (direction: "left" | "right") => {
  console.log(direction);
};
const permissionStore = usePermissionStoreHook();
type TagView = Partial<RouteLocationNormalized>;
/** 固定的标签页 */
let affixTags: TagView[] = [];
/** 判断标签页是否激活 */
const isActive = (tag: TagView) => {
  return tag.path === route.path;
};

/** 判断标签页是否固定 */
const isAffix = (tag: TagView) => {
  return tag.meta?.affix;
};
/** 筛选出固定标签页 */
const filterAffixTags = (routes: RouteRecordRaw[]) => {
  const tags: TagView[] = [];
  routes.forEach((route) => {
    if (isAffix(route)) {
      const tagPath = route.path;
      tags.push({
        fullPath: tagPath,
        path: tagPath,
        name: route.name,
        meta: { ...route.meta }
      });
    }
    if (route.children) {
      const childTags = filterAffixTags(route.children);
      tags.push(...childTags);
    }
  });
  return tags;
};
/** 初始化标签页 */
const initTagsView = () => {
  affixTags = filterAffixTags(permissionStore.manageMenus as RouteRecordRaw[]);

  console.log(permissionStore.manageMenus, affixTags, "manageMenus");
  for (const tag of affixTags) {
    // 必须含有 path 属性
    tag.path && tagsViewStore.addTagView(tag);
  }
};
/** 添加标签页 */
const addTags = (route: RouteLocationNormalizedLoaded) => {
  if (route.path) {
    tagsViewStore.addTagView(route);
  }
};
/** 关闭当前正在操作的标签页 */
const closeSelectedTag = (view: TagView) => {
  tagsViewStore.removeTagView(view);
  // 关闭当前标签页后，如果有其他标签页，则切换到最后一个标签页
  isActive(view) && toLastView(tagsViewStore.tagsViews, view);
};

/** 关闭所有标签页 */
// const closeAllTags = (view: TagView) => {
//   tagsViewStore.removeTagView(view);
//   if (affixTags.some((tag) => tag.path === route.path)) return;
//   toLastView(tagsViewStore.tagsViews, view);
// };

/** 跳转到最后一个标签页 */
const toLastView = (tagsViews: TagView[], view: TagView) => {
  const latestView = tagsViews.slice(-1)[0];
  const fullPath = latestView?.fullPath;
  if (fullPath !== undefined) {
    router.push(fullPath);
  } else {
    // 如果 TagsView 全部被关闭了，则默认重定向到主页

    if (view.path === affixTags[0].path) {
      // 重新加载主页
      router.push({ path: "/redirect" + view.path, query: view.query });
    } else {
      router.push("/");
    }
  }
};

const instance = getCurrentInstance();
/** 鼠标移入添加激活样式 */
const onMouseenter = (index: number) => {
  console.log(index, "index");

  // if (index) activeIndex.value = index;
  toggleClass(true, "schedule-in", instance.refs["schedule" + index][0]);
  toggleClass(false, "schedule-out", instance.refs["schedule" + index][0]);
};
/** 鼠标移出恢复默认样式 */
const onMouseleave = (index: number) => {
  console.log(index, "indexleave");

  // activeIndex.value = -1;
  toggleClass(false, "schedule-in", instance.refs["schedule" + index][0]);
  toggleClass(true, "schedule-out", instance.refs["schedule" + index][0]);
};
const toggleClass = (shouldAdd: boolean, className: string, element: HTMLElement) => {
  // 检查元素是否存在
  if (!element) {
    return;
  }
  // 判断是否需要添加类
  if (shouldAdd) {
    // 如果元素没有这个类，就添加它
    if (!element.classList.contains(className)) {
      element.classList.add(className);
    }
  } else {
    // 如果元素有这个类，就移除它
    if (element.classList.contains(className)) {
      element.classList.remove(className);
    }
  }
};
watch(
  route,
  () => {
    console.log(toRaw(route), tagsViewStore.tagsViews, "route");
    addTags(toRaw(route));
  },
  {
    immediate: true,
    deep: true
  }
);
const scrollbarDom = ref<HTMLDivElement>();
onMounted(() => {
  initTagsView();
  useResizeObserver(scrollbarDom, () => {});
});
</script>
<style scoped lang="scss">
.tags-view {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
  font-size: 14px;
  color: var(--el-text-color-primary);
  background: #fff;
  box-shadow: 0 0 1px #888;
  .tags-view-item {
    position: relative;
    display: inline-block;
    height: 34px;
    padding-left: 6px;
    line-height: 34px;
    cursor: pointer;
    transition: all 0.4s;

    &:not(:first-child) {
      padding-right: 24px;
    }
    .el-icon-close {
      position: absolute;
      top: 50%;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 18px;
      height: 18px;
      color: var(--el-color-primary);
      cursor: pointer;
      border-radius: 4px;
      transition:
        background-color 0.12s,
        color 0.12s;
      transform: translate(0, -50%);

      &:hover {
        color: rgb(0 0 0 / 88%) !important;
        background-color: rgb(0 0 0 / 6%);
      }
    }
  }
  .tag-title {
    padding: 0 4px;
    color: var(--el-text-color-primary);
    text-decoration: none;
  }
  .scroll-container {
    position: relative;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    .tags-view-list {
      position: relative;
      float: left;
      overflow: visible;
      white-space: nowrap;
      list-style: none;
      .tags-view-item {
        transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);

        &:nth-child(1) {
          padding: 0 12px;
        }
      }
    }
  }
}
.arrow-left,
.arrow-right {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 34px;
  color: var(--el-text-color-primary);
}

.arrow-left {
  box-shadow: 5px 0 5px -6px #ccc;

  &:hover {
    cursor: w-resize;
  }
}

.arrow-right {
  border-right: 0.5px solid #ccc;
  box-shadow: -5px 0 5px -6px #ccc;

  &:hover {
    cursor: e-resize;
  }
}

/* 标签线 */
.schedule-active {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: var(--el-color-primary);
}

/* 标签线下鼠标移入显示蓝色进度条 */
.schedule-in {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: var(--el-color-primary);
  animation: schedule-in-width 200ms ease-in;
}

/* 标签线下鼠标移出隐藏蓝色进度条 */
.schedule-out {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background: var(--el-color-primary);
  animation: schedule-out-width 200ms ease-in;
}

@keyframes schedule-in-width {
  from {
    width: 0;
  }

  to {
    width: 100%;
  }
}

@keyframes schedule-out-width {
  from {
    width: 100%;
  }

  to {
    width: 0;
  }
}
</style>
